package com.zhang.map;

import com.zhang.map.Map;
import com.zhang.printer.BinaryTreeInfo;
import com.zhang.二叉树.BinaryTree;
import com.zhang.二叉树.RBTree;

import java.util.*;

/**
 * @author 张吉鑫
 * @Description 红黑树实现TreeMap
 * @date 2021/3/23 20:07
 */
public class TreeMap<K, V> implements Map<K, V>, BinaryTreeInfo {
    private static final boolean RED = false;
    private static final boolean BLACK = true;
    private int size;
    private Node<K, V> root;
    private Comparator<K> comparator;

    public TreeMap() {
        this(null);
    }

    public TreeMap(Comparator<K> comparator) {
        this.comparator = comparator;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        root = null;
    }

    @Override
    public V put(K key, V value) {
        keyNotNullCheck(key);

        if (root == null) {
            root = new Node<>(key, value, null);
            size++;

            afterPut(root);
            return null;
        }
        Node<K, V> node = root;
        Node<K, V> parent = root;
        int cmp = 0;
        while (node != null) {
            cmp = compare(key, node.key);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                V value1 = node.value;
                node.key = key;
                node.value = value;
                return value1;
            }
        }
        Node<K, V> newNode = new Node(key, value, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else if (cmp < 0) {
            parent.left = newNode;
        }
        size++;
        afterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    @Override
    public V remove(K key) {
        Node<K, V> node = node(key);
        if (node == null) {
            return null;
        }

        V value = node.value;

        size--;

        if (node.hasTwoChildren()) {//度为2
            Node<K, V> p = predecessor(node);
            node.key = p.key;
            node.value = p.value;
            node = p;
        }

        Node<K, V> childNode = node.left != null ? node.left : node.right;

        if (childNode != null) {//度为1
            childNode.parent = node.parent;
            if (childNode.parent == null) {//如果删除的节点父节点是null 说明是根节点
                root = childNode;
            } else if (childNode.parent.left == node) {
                childNode.parent.left = childNode;
            } else {
                childNode.parent.right = childNode;
            }
            afterRemove(node, childNode);
        } else if (node.parent == null) {//是叶子节点 又是根节点
            root = null;
            afterRemove(node, null);
        } else {//是叶子节点 度为0
            if (node.parent.left == node) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            afterRemove(node, null);
        }
//        afterRemove(node);
        return value;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (root == null) {
            return false;
        }
        Queue<Node<K,V>> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()){

            Node<K, V> poll = queue.poll();

            if (Objects.equals(value, poll.value)){
                return true;
            }

            if (poll.left != null){
                queue.offer(poll.left);
            }

            if (poll.right != null){
                queue.offer(poll.right);
            }

        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (visitor == null){
            return;
        }
        inorder(visitor);
    }



    /**
     * 中序遍历迭代
     *
     * @param visitor
     */
    private void inorder(Visitor<K, V> visitor) {
        if (root == null) {
            return;
        }
        Deque<Node<K, V>> deque = new LinkedList<>();
        deque.push(root);

        while (!deque.isEmpty()) {
            Node<K, V> node = deque.pop();

            if (node.right != null) {
                deque.push(node.right);
            }

            if (node.isLeaf()) {
                if (visitor.stop){
                    return;
                }
                visitor.visit(node.key, node.value);
            } else {
                deque.push(new Node<>(node.key, node.value, null));
            }

            if (node.left != null) {
                deque.push(node.left);
            }
        }
    }

    /**
     * 通过元素查找节点
     *
     * @param key
     * @return
     */
    private Node<K, V> node(K key) {
        keyNotNullCheck(key);

        if (root == null) {
            return null;
        }

        Node<K, V> node = root;
        while (node != null) {
            int cmp = compare(key, node.key);
            if (cmp == 0) {
                return node;
            } else if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }

        return null;
    }

    /**
     * 添加后调整平衡
     * @param node
     */
    private void afterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;

        if (parent == null) {
            black(node);
            return;
        }

        /**
         * parent是黑色节点 不用做任何处理
         */
        if (isBlack(parent)) {
            return;
        }

        /**
         * 判断祖父节点是否是黑色
         */
        Node<K, V> grand = parent.parent;
        if (isBlack(parent.sibling())) {

            grand = red(grand);

            if (parent.isLeftChild()) {//L
                if (node.isLeftChild()) {//LL
                    parent = black(parent);
                } else {//LR
                    node = black(node);
                    rotateLeft(parent);
                }
                rotateRight(grand);
            } else {//R
                if (node.isLeftChild()) {//RL
                    node = black(node);
                    rotateRight(parent);
                } else {//RR
                    parent = black(parent);
                }
                rotateLeft(grand);
            }
        } else {//叔父节点是红色的
            parent = black(parent);
            black(parent.sibling());
            afterPut(red(grand));
        }

    }

    /**
     * 删除后调整平衡
     * @param node
     * @param childNode
     */
    private void afterRemove(Node<K, V> node, Node<K, V> childNode) {
        //如果删除的节点是红色 直接删除
        if (isRed(node)) {
            return;
        }

        //如果替代的节点是红色的 把替代的节点染成黑色
        if (isRed(childNode)) {
            black(childNode);
            return;
        }

        Node<K, V> parent = node.parent;
        //如果父节点是空的 说明删除节点就是根节点
        if (parent == null) {
            return;
        }
        //获取删除节点的兄弟节点
        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;


        //如果兄弟节点在父节点的左边
        if (sibling.isLeftChild()) {
            //如果兄弟节点是红色的
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateRight(parent);
                sibling = parent.left;
            }
            //如果兄弟节点两个子节点都是黑色的
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                //如果父类是黑色节点 会产生下溢 再次调用方法 把父类节点当初删除节点处理
                boolean b = colorOf(parent);
                red(sibling);
                black(parent);
                if (b) {
                    afterRemove(parent, null);
                }
            } else {
                //兄弟节点至少有一个红色节点
                boolean b = colorOf(parent);
                if (isRed(sibling.right)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }
                color(sibling, b);
                black(parent);
                black(sibling.left);
                rotateRight(parent);
            }
        } else {
            //如果兄弟节点是红色的
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateLeft(parent);
                sibling = parent.right;
            }
            //如果兄弟节点两个子节点都是黑色的
            if (isBlack(sibling.right) && isBlack(sibling.left)) {
                //如果父类是黑色的 会产生下溢现象 把父类节点当作删除节点 重新调用方法
                boolean b = colorOf(parent);
                red(sibling);
                black(parent);
                if (b) {
                    afterRemove(parent, null);
                }
            } else {
                //兄弟节点至少有一个红色节点
                boolean b = colorOf(parent);
                if (isRed(sibling.left)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }
                color(sibling, b);
                black(parent);
                black(sibling.right);
                rotateLeft(parent);
            }
        }
    }

    /**
     * 前驱节点
     *
     * @param node
     * @return
     */
    private Node<K, V> predecessor(Node<K, V> node) {

        if (node == null) {
            return null;
        }

        if (node.left != null) {
            Node<K, V> n = node.left;
            while (n.right != null) {
                n = n.right;
            }
            return n;
        }
        while (node.parent != null && node == node.parent.left) {
            node = node.parent;
        }

        return node.parent;
    }

    /**
     * 后继节点
     *
     * @param node
     * @return
     */
    private Node<K, V> successor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        if (node.right != null) {
            Node<K, V> s = node.right;
            while (s.left != null) {
                s = s.left;
            }
            return s;
        }
        while (node.parent != null && node == node.parent.right) {
            node = node.parent;
        }

        return node.parent;
    }


    /**
     * 左旋转
     *
     * @param grand
     */
    private void rotateLeft(Node<K, V> grand) {
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        grand.right = child;
        parent.left = grand;

        afterRotate(grand, parent, child);
    }

    /**
     * 右旋转
     *
     * @param grand
     */
    private void rotateRight(Node<K, V> grand) {
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        grand.left = child;
        parent.right = grand;

        afterRotate(grand, parent, child);
    }

    /**
     * 旋转后 更新高度
     *
     * @param grand
     * @param parent
     * @param child
     */
    private void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        if (grand.parent == null) {
            root = parent;
        } else if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else {
            grand.parent.right = parent;
        }
        parent.parent = grand.parent;
        grand.parent = parent;

        if (child != null) {
            child.parent = grand;
        }

    }

    /**
     * 染色的方法
     *
     * @param node
     * @param color
     * @return
     */
    private Node<K, V> color(Node<K, V> node, boolean color) {
        if (node == null) {
            return node;
        }
        node.color = color;
        return node;
    }

    /**
     * 染成红色
     *
     * @param node
     * @return
     */
    private Node<K, V> red(Node<K, V> node) {
        return color(node, RED);
    }

    /**
     * 染成黑色
     *
     * @param node
     * @return
     */
    private Node<K, V> black(Node<K, V> node) {
        return color(node, BLACK);
    }

    /**
     * 查看节点颜色
     *
     * @param node
     * @return
     */
    private boolean colorOf(Node<K, V> node) {
        return node == null ? BLACK : node.color;
    }

    /**
     * 判断节点是否为黑色
     *
     * @param node
     * @return
     */
    private boolean isBlack(Node<K, V> node) {
        return colorOf(node) == BLACK;
    }

    /**
     * 判断节点是否为红色
     *
     * @param node
     * @return
     */
    private boolean isRed(Node<K, V> node) {
        return colorOf(node) == RED;
    }

    /**
     * 比较器
     *
     * @param e1
     * @param e2
     * @return
     */
    private int compare(K e1, K e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<K>) e1).compareTo(e2);
    }

    /**
     * 判断元素是否为空
     *
     * @param key
     */
    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("key must not be null!");
        }
    }

    @Override
    public Object root() {
        return root;
    }

    @Override
    public Object left(Object node) {
        return ((Node<K, V>) node).left;
    }

    @Override
    public Object right(Object node) {
        return ((Node<K, V>) node).right;
    }

    @Override
    public Object string(Object node) {
        return node;
    }

    private static class Node<K, V> {
        K key;
        V value;
        boolean color = RED;
        Node<K, V> left;
        Node<K, V> right;
        Node<K, V> parent;

        public Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        /**
         * 判断是否为叶子节点
         *
         * @return
         */
        public boolean isLeaf() {
            return left == null && right == null;
        }

        /**
         * 判断是否有两个子节点
         *
         * @return
         */
        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        /**
         * 判断是否是父节点的左子节点
         *
         * @return
         */
        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        /**
         * 判断是否是父亲节点的右子节点
         *
         * @return
         */
        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        /**
         * 返回兄弟节点
         *
         * @return
         */
        public Node<K, V> sibling() {
            if (isLeftChild()) {
                return parent.right;
            }
            if (isRightChild()) {
                return parent.left;
            }

            return null;
        }

        @Override
        public String toString() {
            String str = "";
            if (color == RED) {
                str = "【R】_";
            }
            return str + key.toString() + "," + value.toString();
        }
    }
}
